<template>
  <div class="screen-container">
    <div id="cesiumContainer" style="width: 100%; height: 100%"></div>
    <div id="hud" class="hud-container">
      <div v-for="(value, key) in hudData" :key="key" class="hud-item">
        <span class="hud-label">{{ key }}:</span>
        <span class="hud-value">{{ value }}</span>
      </div>
    </div>
  </div>
</template>
  
  <script setup>
  import * as Cesium from 'cesium';
  import { onMounted, onUnmounted, ref } from 'vue';
  
  // 定义Cesium viewer响应式引用
  const viewerRef = ref(null);
  
  // 定义HUD数据响应式对象
  const hudData = ref({
    '当前速度': '0.000 km/s',
    '轨道高度': '0.0 km',
    '机动剩余': '0.00 m/s'
  });
  
  // 定义卫星实体引用
  const satelliteEntity = ref(null);
  // 定义轨道数据
  const trajectoryData = ref([]);
  // 定义修正点数据（示例）
  const correctionsData = ref([
    { time: 720878800, position: [116.39, 39.9, 500000], deltaV: 10.5 },
    { time: 720880000, position: [126.39, 35.9, 520000], deltaV: 5.2 }
  ]);
  // 定义剩余推进剂
  const remainingDeltaV = ref(100.0);
  
  // 在组件挂载时初始化Cesium
  onMounted(async () => {
    // 设置 Cesium 的访问令牌
    Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4MTNlOWJkNy01NTU0LTQ3ZWQtYmM3Yi1mNGViODFhOGY3NzQiLCJpZCI6MjgwODczLCJpYXQiOjE3NDEwNzIwNTl9.v7K25kZiBHwarMikqFQEH-NROT27E4JjdsmpUULH4J0";
  
    // 创建Cesium查看器并保存到响应式引用
    viewerRef.value = new Cesium.Viewer('cesiumContainer', {
      terrainProvider: Cesium.createWorldTerrain(),
      timeline: true,
      animation: true,
      shouldAnimate: true,
      baseLayerPicker: true,
      geocoder: false,
      homeButton: true,
      infoBox: true,
      sceneModePicker: true,
      selectionIndicator: true,
      navigationHelpButton: true
    });
  
    // 加载轨道数据
    await loadTrajectoryData();
  
    // 如果成功加载了轨道数据
    if (trajectoryData.value.length > 0) {
      // 设置时钟范围
      const startTime = Cesium.JulianDate.fromDate(new Date(2022, 10, 5)); // 2022-11-05
      const stopTime = Cesium.JulianDate.addSeconds(startTime, trajectoryData.value[trajectoryData.value.length - 1].time - trajectoryData.value[0].time, new Cesium.JulianDate());
      
      viewerRef.value.clock.startTime = startTime.clone();
      viewerRef.value.clock.stopTime = stopTime.clone();
      viewerRef.value.clock.currentTime = startTime.clone();
      viewerRef.value.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
      viewerRef.value.clock.multiplier = 50; // 50倍速播放
      viewerRef.value.timeline.zoomTo(startTime, stopTime);
  
      // 创建卫星位置的SampledPositionProperty
      const position = new Cesium.SampledPositionProperty();
      
      // 添加所有位置采样点
      trajectoryData.value.forEach(point => {
        const time = Cesium.JulianDate.addSeconds(startTime, point.time - trajectoryData.value[0].time, new Cesium.JulianDate());
        const pos = new Cesium.Cartesian3(point.x, point.y, point.z);
        position.addSample(time, pos);
      });
  
      // 创建CZML数据用于轨道路径可视化
      const czmlData = generateCzmlFromTrajectory(trajectoryData.value, startTime);
      viewerRef.value.dataSources.add(Cesium.CzmlDataSource.load(czmlData));

      // 添加卫星实体
      satelliteEntity.value = viewerRef.value.entities.add({
        name: '卫星',
        position: position,
        orientation: new Cesium.VelocityOrientationProperty(position),
        model: {
          uri: './models/glb/satellite.glb', // 确保此路径正确
          scale: 5000,
          minimumPixelSize: 64
        },
        path: {
          resolution: 1,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.3,
            color: Cesium.Color.YELLOW
          }),
          width: 3,
          leadTime: 0,
          trailTime: 60 * 60 // 显示1小时的轨迹
        }
      });
  
      // 添加修正点标记
      addCorrectionMarkers(viewerRef.value, correctionsData.value, startTime);

      // 设置相机跟随卫星
      viewerRef.value.trackedEntity = satelliteEntity.value;

      // 实时更新HUD数据
      viewerRef.value.clock.onTick.addEventListener(clock => {
        updateHudData(viewerRef.value, position, clock.currentTime);
      });
    }
  });
  
  // 在组件卸载时清理资源
  onUnmounted(() => {
    if (viewerRef.value) {
      viewerRef.value.destroy();
    }
  });
  
  /**
   * 加载轨道数据
   * 从transformed_data.txt文件中读取ECEF坐标数据
   */
  async function loadTrajectoryData() {
    try {
      // 使用fetch API获取数据文件
      const response = await fetch('./models/transformed_data.txt');
      if (!response.ok) {
        throw new Error('HTTP error! status: ${response.status}');
      }
      
      const text = await response.text();
      const lines = text.split('\n');
      
      // 跳过头部注释行（以#开头的行）
      const dataLines = lines.filter(line => !line.trim().startsWith('#') && line.trim().length > 0);
      
      // 解析每一行数据
      const data = dataLines.map(line => {
        const values = line.trim().split(/\s+/);
        return {
          time: parseFloat(values[0]),       // 时间(秒)
          x: parseFloat(values[1]) * 1000,   // X_ECEF(米)，转换为米
          y: parseFloat(values[2]) * 1000,   // Y_ECEF(米)，转换为米
          z: parseFloat(values[3]) * 1000,   // Z_ECEF(米)，转换为米
          vx: parseFloat(values[4]) * 1000,  // Vx(米/秒)，转换为米/秒
          vy: parseFloat(values[5]) * 1000,  // Vy(米/秒)，转换为米/秒
          vz: parseFloat(values[6]) * 1000   // Vz(米/秒)，转换为米/秒
        };
      });
      
      trajectoryData.value = data;
      console.log(`成功加载了 ${data.length} 条轨道数据点`);
    } catch (error) {
      console.error('加载轨道数据失败:', error);
    }
  }
  
  /**
   * 从轨道数据生成CZML
   * @param {Array} data - 轨道数据数组
   * @param {Cesium.JulianDate} startTime - 起始时间
   * @returns {Array} CZML数据
   */
  function generateCzmlFromTrajectory(data, startTime) {
    // 创建CZML文档头
    const czml = [{
      id: "document",
      name: "卫星轨道",
      version: "1.0"
    }];
  
    // 创建轨道路径
    const positions = [];
    const times = [];
  
    data.forEach(point => {
      const time = Cesium.JulianDate.addSeconds(startTime, point.time - data[0].time, new Cesium.JulianDate());
      times.push(Cesium.JulianDate.toIso8601(time));
      positions.push(point.x, point.y, point.z);
    });
  
    // 添加轨道路径实体
    czml.push({
      id: "path",
      name: "卫星轨道路径",
      availability: `${times[0]}/${times[times.length - 1]}`,
      path: {
        material: {
          solidColor: {
            color: {
              rgba: [0, 255, 255, 255]
            }
          }
        },
        width: 2,
        leadTime: 0,
        trailTime: 3600, // 1小时的轨迹
        resolution: 120  // 每120秒一个点
      },
      position: {
        epoch: times[0],
        cartesian: positions
      }
    });
  
    return czml;
  }
  
  /**
   * 添加轨道修正点标记
   * @param {Cesium.Viewer} viewer - Cesium查看器
   * @param {Array} corrections - 修正点数据
   * @param {Cesium.JulianDate} startTime - 起始时间
   */
  function addCorrectionMarkers(viewer, corrections, startTime) {
    corrections.forEach(correction => {
      const time = Cesium.JulianDate.addSeconds(startTime, correction.time - trajectoryData.value[0].time, new Cesium.JulianDate());
      
      // 将经纬度高度转换为Cartesian3坐标
      const position = Cesium.Cartesian3.fromDegrees(
        correction.position[0], 
        correction.position[1], 
        correction.position[2]
      );
      
      viewer.entities.add({
        position: position,
        billboard: {
          image: './images/1211.png', // 确保此路径正确
          scale: 0.5,
          color: Cesium.Color.RED
        },
        label: {
          text: `ΔV: ${correction.deltaV.toFixed(1)} m/s`,
          font: '14px sans-serif',
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.BLACK,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, -10)
        },
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({
            start: time,
            stop: Cesium.JulianDate.addSeconds(time, 3600, new Cesium.JulianDate()) // 显示1小时
          })
        ])
      });
    });
  }
  
  /**
   * 更新HUD数据
   * @param {Cesium.Viewer} viewer - Cesium查看器
   * @param {Cesium.SampledPositionProperty} position - 卫星位置属性
   * @param {Cesium.JulianDate} currentTime - 当前时间
   */
  function updateHudData(viewer, position, currentTime) {
    // 获取当前位置
    const currentPosition = position.getValue(currentTime);
    if (!currentPosition) return;
    
    // 计算当前速度
    const nextTime = Cesium.JulianDate.addSeconds(currentTime, 1, new Cesium.JulianDate());
    const nextPosition = position.getValue(nextTime);
    
    if (nextPosition) {
      // 计算速度（米/秒）
      const velocity = Cesium.Cartesian3.distance(currentPosition, nextPosition);
      
      // 计算高度（地球表面到卫星的距离）
      const cartographic = Cesium.Cartographic.fromCartesian(currentPosition);
      const altitude = cartographic.height / 1000; // 转换为千米
      
      // 更新HUD数据
      hudData.value = {
        '当前速度': `${(velocity / 1000).toFixed(3)} km/s`,
        '轨道高度': `${altitude.toFixed(1)} km`,
        '机动剩余': `${remainingDeltaV.value.toFixed(2)} m/s`
      };
    }
  }
  </script>
  
  <style scoped>
  .screen-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  #cesiumContainer {
    flex: 1;
  }

  .hud-container {
    position: absolute;
    top: 10px;
    right: 10px;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 10px;
    border-radius: 5px;
    font-family: 'Arial', sans-serif;
    z-index: 1000;
  }
  
  .hud-item {
    margin: 5px 0;
  }
  
  .hud-label {
    font-weight: bold;
    margin-right: 5px;
  }
  
  .hud-value {
    color: #4caf50;
  }
  </style>
